package com.vmj.instructions.references;

import com.vmj.common.BytesReader;
import com.vmj.heap.*;
import com.vmj.heap.VMClass;
import com.vmj.heap.VMObject;
import com.vmj.instructions.base.Index16Instruction;
import com.vmj.rtda.Frame;
import com.vmj.rtda.OperandStack;

/**
 * Created by yangshoujun on 2017/9/9 上午10:43.
 */
public class ANewArray extends Index16Instruction {

    int index;

    public void fetchOperands(BytesReader reader) {
        index = reader.readShort();
    }

    public void execute(Frame frame) {
        RuntimeConstantPool cp = frame.getMethod().getClazz().getRuntimeConstantPool();
        ClassRef classRef = (ClassRef) cp.getConstant(index).getValue();
        VMClass componentClass = classRef.resolvedClass();
        OperandStack stack = frame.getOperandStack();
        int count = stack.popInt();
        if(count < 0) {
            throw new RuntimeException("java.lang.NagativeArraySizeException");
        }

        VMClass clazz = componentClass.getArrayClass();
        VMObject array = VMObject.newArray(clazz, count);
        stack.pushRef(array);
    }
}
